package com.sichen.member.service.impl;

import com.alibaba.fastjson2.JSON;
import com.sichen.common.utils.HttpUtils;
import com.sichen.member.dao.MemberLevelDao;
import com.sichen.member.entity.MemberLevelEntity;
import com.sichen.member.exception.PhoneException;
import com.sichen.member.exception.UsernameException;
import com.sichen.member.vo.*;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sichen.common.utils.PageUtils;
import com.sichen.common.utils.Query;

import com.sichen.member.dao.MemberDao;
import com.sichen.member.entity.MemberEntity;
import com.sichen.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberDao memberDao = this.baseMapper;
        MemberEntity entity = new MemberEntity();
        // 设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLevel();
        entity.setLevelId(levelEntity.getId());
        // 设置用户设置的属性
        // 需要先检查手机号和用户名是否唯一 , 为了让
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());

        entity.setUsername(vo.getUserName());
        entity.setMobile(vo.getPhone());
        entity.setNickname(vo.getUserName());

        // 密码要进行加密存储 , 使用MD5进行加密存储
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassWord());
        entity.setPassword(encode);

        // 其他的默认信息

        memberDao.insert(entity);
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        // 1.去数据库查询
        MemberDao baseMapper = this.baseMapper;
        MemberEntity entity = baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", vo.getLoginAccount())
                .or().eq("mobile", vo.getLoginAccount()));
        if (entity == null){
            // 登录失败
            return null;
        }else {
            // 1.获取到数据库的password
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            // 密码匹配 , matches第一个参数是明文密码 , 后一个参数是MD5加密密码
            boolean b = passwordEncoder.matches(vo.getPassWord(), passwordDb);
            if (b){
                return entity;
            } else {
                return null;
            }
        }
    }

    /**
     * 使用社交账号登录 , 包含登录和注册逻辑
     * @param socialUserVo
     * @return
     */
    @Override
    public MemberEntity login(SocialUserVo socialUserVo) throws Exception {
        OAuthUserVo oAuthUserVo = extracted(socialUserVo.getAccess_token());
        if (oAuthUserVo != null){
            // 获取用户信息成功
            // 判断当前社交用户是否已经登录过系统
            MemberDao memberDao = this.baseMapper;
            MemberEntity memberEntity = memberDao.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", oAuthUserVo.getId()));
            if (memberEntity != null) {
                // 这个用户已经注册 , 更新令牌和过期时间即可
                MemberEntity updata = new MemberEntity();
                updata.setId(memberEntity.getId());
                updata.setAccessToken(socialUserVo.getAccess_token());
                updata.setExpiresIn(socialUserVo.getExpires_in());
                memberDao.updateById(updata);

                memberEntity.setAccessToken(socialUserVo.getAccess_token());
                memberEntity.setExpiresIn(socialUserVo.getExpires_in());
                return memberEntity;
            }else {
                // 没有查到当前社交用户的信息
                MemberEntity regist = new MemberEntity();
                regist.setNickname(oAuthUserVo.getName());
                regist.setHeader(oAuthUserVo.getAvatar_url());

                regist.setSocialUid(oAuthUserVo.getId());
                regist.setAccessToken(socialUserVo.getAccess_token());
                regist.setExpiresIn(socialUserVo.getExpires_in());
                memberDao.insert(regist);
                return regist;
            }
        } else {
            return null;
        }
    }

    /**
     * 根据token获取用户信息
     * @param access_token token
     * @throws Exception
     */
    private OAuthUserVo extracted(String access_token) throws Exception {
        // 获取用户的全部信息 , https://gitee.com/api/v5/user
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("access_token", access_token);
        HttpResponse resp = HttpUtils.doGet("https://gitee.com", "/api/v5/user",
                "get", null, hashMap);
        if (resp.getStatusLine().getStatusCode() == 200) {
            String userAttrJson = EntityUtils.toString(resp.getEntity());
            AuthGiteeUserAttrVo authGiteeUserAttrVo = JSON.parseObject(userAttrJson, AuthGiteeUserAttrVo.class);
            OAuthUserVo vo = new OAuthUserVo();
            BeanUtils.copyProperties(authGiteeUserAttrVo, vo);
            return vo;
        }else{
            return null;
        }
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneException{
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0){
            throw new PhoneException();
        }
    }

    @Override
    public void checkUsernameUnique(String userName) throws UsernameException{
        MemberDao memberDao = this.baseMapper;
        Integer count = memberDao.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0){
            throw new UsernameException();
        }
    }
}